<template>
  <el-dialog :title="title" v-model="dialogVisible" destroy-on-close width="60%" :before-close="handleClose">
    <div class="location-picker-container">
      <div class="main-content">
        <div class="map-container">
          <div id="map"></div>
        </div>

        <div class="info-panel">
          <div class="search-box">
            <el-input placeholder="地点关键字搜索" v-model="keyword" @keyup.enter="searchPlace($event.target.value)">
              <template #append>
                <el-icon style="cursor: pointer" @click="searchPlace"><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="location-info">
            <div class="info-item">
              <label>详细地址：</label>
              <div>{{ selectedLocation.address || '请在地图上选择位置' }}</div>
            </div>

            <div class="info-item">
              <label>经纬度：</label>
              <div>{{ selectedLocation.location || '暂无' }}</div>
            </div>

            <div class="instructions">
              <h3>使用说明</h3>
              <ul>
                <li>在地图上点击选择位置</li>
                <li>在搜索框输入关键字搜索地点</li>
                <li>选择城市可以缩小搜索范围</li>
                <li>点击确认选择按钮完成位置选择</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" style="text-align: center; padding: 10px 0px 50px 0px">
      <div class="action-buttons">
        <el-button type="primary" @click="confirmSelection">确认选择</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, defineEmits, nextTick, onMounted } from 'vue'
import { Search, Location } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'

import iconUrl from 'leaflet/dist/images/marker-icon.png'

// console.log(iconUrl)

const title = ref('选择位置')

const map = ref(null)
const marker = ref(null)

const selectedLocation = ref({
  location: '',
  address: '',
  lat: 0,
  lng: 0
})
const keyword = ref('')
// 初始化地图
const initMap = () => {
  // 只能按这种方式 否则地图无法显示
  if (import.meta.env.PROD) {
    require('leaflet.chinatmsproviders')
  }

  let tk = 'e9194a54'
  const tianImage = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
    key: tk,
    maxZoom: 18,
    minZoom: 5
  })
  //天地图注记
  const tianNotes = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
    key: tk,
    maxZoom: 18,
    minZoom: 5
  })

  // 高德电子地图
  const amp = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
    maxZoom: 18,
    minZoom: 5
  })
  const tiandiMap = L.layerGroup([tianImage, tianNotes], { maxZoom: 18, minZoom: 5 })

  map.value = L.map('map', {
    zoom: 15,
    preferCanvas: true,
    center: [26.081528, 103.234025],
    layers: [amp]
  })

  //

  const ctl = L.control.layers({ 天地图: tiandiMap, 电子地图: amp })
  ctl.addTo(map.value)

  handleSetMapView()
  // 添加点击地图事件
  map.value.on('click', ({ latlng }) => {
    selectedLocation.value.location = `[${latlng.lng.toFixed(6)},${latlng.lat.toFixed(6)}]`
    selectedLocation.value.lng = latlng.lng
    selectedLocation.value.lat = latlng.lat
    setMarker(latlng)
    // console.log(latlng)
  })
}

onMounted(() => {
  // initMap()
  // ElMessage.warning('位置选择生产环境和开发环境需要使用不同写法，尚未兼容。')
})

// 设置标记点
const setMarker = (lnglat) => {
  // 清除现有标记
  if (marker.value) {
    marker.value.remove()
  }
  // 创建新标记
  let newMarker = L.marker(lnglat, {
    icon: L.icon({
      iconUrl: iconUrl,
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41]
    })
  })
  // console.log(newMarker)
  newMarker.bindPopup('已选位置')
  marker.value = newMarker
  marker.value.addTo(map.value)
  map.value.setView(lnglat)
}

// 获取地址信息
const getAddress = (lnglat) => {
  const geocoder = new AMap.Geocoder({
    city: '530113',
    radius: 1000
  })

  geocoder.getAddress(lnglat, (status, result) => {
    if (status === 'complete' && result.regeocode) {
      selectedLocation.value.address = result.regeocode.formattedAddress
      selectedLocation.value = `${lnglat.lng.toFixed(6)}, ${lnglat.lat.toFixed(6)}`
    } else {
      ElMessage.error('获取地址失败')
    }
  })
}

// 搜索地点
const searchPlace = () => {
  if (!keyword.value) {
    ElMessage.warning('请输入搜索关键字')
    return
  }
  ElMessage.warning('暂不支持搜索关键字')
}

const emits = defineEmits(['change'])
// 确认选择
const confirmSelection = () => {
  if (!selectedLocation.value) {
    ElMessage.warning('请先选择位置')
    return
  }
  ElMessage.success(`位置已选择: ${selectedLocation.value.location}`)
  dialogVisible.value = false
  emits('change', selectedLocation.value)
  // 这里可以触发一个事件或回调函数，将选择的位置信息传递给父组件
}

const dialogVisible = ref(false)

const handleShow = (location, titleLocation) => {
  dialogVisible.value = true
  selectedLocation.value.location = location
  ElMessage.warning('位置选择生产环境和开发环境需要使用不同写法，尚未兼容。当前只兼容生产环境。')
  title.value = titleLocation ?? '选择位置'
  // console.log(location)
  nextTick(initMap)
}
const handleClose = (done) => {
  dialogVisible.value = false
  if (map.value) {
    map.value.remove()
    map.value = null
  }
}
const handleSetMapView = () => {
  let location = selectedLocation.value.location
  if (!location) {
    return
  }
  let lnglat = JSON.parse(location)
  let postion = {
    lng: lnglat[0],
    lat: lnglat[1]
  }
  console.log(postion)
  map.value.setView(postion)
  setMarker(postion)
}

defineExpose({
  handleShow
})
</script>

<style>
.location-picker-container {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.main-content {
  display: flex;
  min-height: 500px;
}
.map-container {
  flex: 7;
  position: relative;
}
#map {
  width: 100%;
  height: 100%;
}
.info-panel {
  flex: 3;
  padding: 20px;
  border-left: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}
.search-box {
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
}
.location-info {
  flex: 1;
  padding: 20px 0;
}
.info-item {
  margin-bottom: 15px;
}
.info-item label {
  display: block;
  color: #888;
  margin-bottom: 5px;
  font-size: 14px;
}
.info-item div {
  font-size: 16px;
  word-break: break-all;
}
.action-buttons {
  padding: 15px 0;
  text-align: center;
}
.marker-content {
  color: #409eff;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
}
.instructions {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}
.instructions h3 {
  margin-bottom: 10px;
  color: #409eff;
}
.instructions ul {
  padding-left: 20px;
  line-height: 1.6;
}
.instructions li {
  margin-bottom: 8px;
}
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  .map-container {
    height: 350px;
  }
  .info-panel {
    border-left: none;
    border-top: 1px solid #e6e6e6;
  }
}
</style>
